﻿using System.Collections.Generic;
using UnityEngine;

public class MathUtil
{
    // anticlockwise is positive, clockwise is negative
    /// <summary>
    /// 计算两个向量的夹角
    /// 逆时针方向为正 顺时针方向为负
    /// 值域为 -180 到 180
    /// </summary>
    /// <param name="v1"> </param>
    /// <param name="v2"></param>
    /// <returns></returns>
    public static XNumber GetRealAngle(XVector3 v1, XVector3 v2)
    {
        if (v1 == XVector3.zero || v2 == XVector3.zero)
            return 0;
        v1.y = 0;
        v2.y = 0;  // 保证在xz平面
        XNumber angle = XVector3.Angle(v1, v2);
        if (XVector3.Cross(v1, v2).y > 0)
        {
            // left
            angle = -angle;
        }

        return angle;
    }

    public static XNumber GetRealAngle3D(XVector3 v1, XVector3 v2)
    {
        if (v1 == XVector3.zero || v2 == XVector3.zero)
            return 0;
        XNumber angle = XVector3.Angle(v1, v2);
        if (XVector3.Cross(v1, v2).y > 0)
        {
            // left
            angle = -angle;
        }

        return angle;
    }

    //一元二次方程, axx + bx + c = 0;
    public static void QuadraticEquation(XNumber a, XNumber b, XNumber c, out XNumber? x1, out XNumber? x2)
    {
        var keyValue = b * b - 4 * a * c;
        if (keyValue < 0)
        {
            x1 = null;
            x2 = null;
        }
        else if (keyValue == 0)
        {
            x1 = -b / (2 * a);
            x2 = null;
        }
        else
        {
            var r = XIntMath.Sqrt(keyValue);
            x1 = (-b + r) / (2 * a);
            x2 = (-b - r) / (2 * 2);
        }
    }
}